function [DFILE] = synch_file(DFILE_in, sf)
% Synchronize data with selected file if necessary
% This routine needs an error return...

global CONTROL
global VOLTAGE

if(nargin ~= 2)
   Error('synch_file: Needs 2 arguments');
end;
if(sf <= 0)
    Error('synch_file: No selection from database?');
end;

% get the control(sf) record list - this is the desired one
if(~check_field(CONTROL(sf),'reclist')) % If this field is present, it overrides the simple record list.
   RecList=sprintf('%d;%d/%d', number_arg(CONTROL(sf).recbeg), number_arg(CONTROL(sf).recend), number_arg(CONTROL(sf).skip));
else
   RecList=CONTROL(sf).reclist;
end
[RL, err] = record_parse(RecList); % always parse it out and get the list 

% now determine what we need to do:
if(isempty(DFILE_in)) % no DFILE, then ALWAYS load the data from scratch
   truefile = parse_filename(CONTROL(sf).path, CONTROL(sf).filename); % get the filename like this...
   [p f e] = fileparts(truefile);
   mode = getdatamode;
   QueMessage(sprintf('(Empty DFILE) Accessing %s Recs: %s',f, RecList));
   drawnow
   [DFILE, err] = readdatac_window(truefile, RL, sf, mode, 1);
   return;
end;

% DFILE_in contains information, so lets compare

if(~strcmp([DFILE_in.filename DFILE_in.ext], CONTROL(sf).filename) ...
      | ~isempty(setxor(RL, DFILE_in.record)) | (size(VOLTAGE, 1) ~= length(RL))) % not the same file or does not contain the same records
   truefile = parse_filename(CONTROL(sf).path, CONTROL(sf).filename); % get the filename like this...
   [p f e] = fileparts(truefile);
   
%   QueMessage(sprintf('Accessing File %s Recs: %s',f, RecList));
   drawnow
   mode = getdatamode;
   [DFILE, err] = readdatac_window(truefile, RL, sf, mode, 1);
else
   % if they were the same, we've already copied input to output
   [p f e] = fileparts(CONTROL(sf).filename);
%   QueMessage(sprintf('synch_file: File %s is in memory', f));
	DFILE = DFILE_in; % copy it over to output...
end;
drawnow
return;
